#!/bin/bash
HOSTNAME="localhost"
EMAIL_CONTENT=""
RANDOMLONG=""
RANDOMSHORT=""

HEADFILE=$1
CONTFILE=$2
TAILFILE=$3
IMAGEFILE=$4
ACOTFILE=$5

HEADCONTENT=`cat $HEADFILE`
TAILCONTENT=`cat $TAILFILE`

Usage(){
	echo "sendmail.sh <template> <content> <account>"
}

Random(){
	RANDOMLONG=`dd if=/dev/urandom count=128 bs=1 2>&1|md5sum|cut -b -25`
	RANDOMSHORT=`dd if=/dev/urandom count=128 bs=1 2>&1|md5sum|cut -b -15`
}

PrepareMail(){
	AppendEContent "EHLO $HOSTNAME"
	AppendEContent "MAIL FROM:<Edward@localhost>"
	AppendEContent "RCPT TO:<$1>"
	AppendEContent "DATA"
	AppendEContent "From:\"=?utf8?B?""`echo 你好|base64`""?=\"<Edward@localhost>"
	AppendEContent "To:$1"
	AppendEContent "Date:""`date -R`"
	Random
	AppendEContent "Message-Id:$RANDOMLONG@$RANDOMSHORT"
	AppendEContent "Subject:=?utf8?B?""`echo -E "$2"|base64`""?="
	AppendEContent "Content-Type: multipart/related;"
	AppendEContent "        boundary=\"_176_6FCAC368B40138458BCDF7B445CC2D4D579CB352EDCNHZEXCMS01al_\";"
	AppendEContent "        type=\"multipart/alternative\""
	AppendEContent "MIME-Version: 1.0"
	AppendEContent ""
	AppendEContent "--_176_6FCAC368B40138458BCDF7B445CC2D4D579CB352EDCNHZEXCMS01al_"
	AppendEContent "Content-Type: text/html;"
	AppendEContent "	charset=\"utf8\""
	AppendEContent "Content-Transfer-Encoding: base64"
	AppendEContent ""

	TESTCONTENT=$HEADCONTENT
	TESTCONTENT=$TESTCONTENT$3
	TESTCONTENT=$TESTCONTENT$TAILCONTENT
	echo "$TESTCONTENT"
	AppendEContent "`echo -E "$TESTCONTENT"|base64 -w 76`"
	AppendEContent "`cat $IMAGEFILE`"
	AppendEContent $'\r'$'\n'"."
	AppendEContent "QUIT"
#	echo "$EMAIL_CONTENT"
}

AppendEContent(){
	EMAIL_CONTENT=$EMAIL_CONTENT$1$'\r'$'\n'
}

ClearEContent(){
	EMAIL_CONTENT=""
}

if [ $# -lt 3 ]
then
	Usage
	exit 1
fi

CONTENT=""
SUBJECT=""
ACCOUNT=""
exec 10<$CONTFILE
while read ACCOUNT
do
	read -u 10 SUBJECT
	read -u 10 CONTENT
	PrepareMail "$ACCOUNT" "$SUBJECT" "$CONTENT"
	ClearEContent
done < $ACOTFILE
 

